<!--
 * @company : 版权所属 四川北星惯牌科技有限公司
 * @contact : 刘经理 19326416371
 -->
<template>
	<view class="payment-box flex-row-center w100">
		<view class="payment-content flex-center w100">
			<view class="price-box flex-center">
				<text class="unit">￥</text>
				<text class="price">{{groupInfo.cost}}</text>
			</view>
			<!-- 			<view class="tips-box flex-center w100" v-if="orderInfo">
				<text class="tips">请在</text>
				<text class="timer">{{orderInfo.time_expire}}</text>
				<text class="tips">前完成支付</text>
			</view> -->
			<view class="tips-box flex-center w100" v-if="groupInfo.levelInfo">
				<text class="tips">当前等级组队基础费用</text>
				<text class="timer">￥{{groupInfo.levelInfo.basic_price}}</text>
			</view>
		</view>
		<view class="team-content">
			<view class="myTeamItem-head flex-row-center">
				<view class="head-left flex-row-center">
					<image src="/static/group/myTeam_icon.png" class="myTeam_icon" mode=""></image>
					<text class="team-name">{{groupInfo.title}}</text>
				</view>
				<!-- 状态 -->
				<text class="team-state">待支付</text>
			</view>
			<!-- 内容 -->
			<view class="myTeamItem-content flex">
				<image :src="groupInfo.mainImg" class="myTeamItem-img" mode="aspectFill"></image>
				<view class="myTeamItem-info">
					<!-- 座位情况 -->
					<text class="describe">{{groupInfo.describe}}</text>
					<view class="address-box flex-row-center w100">
						<up-icon name="map-fill" class="icon" color="#ccc" size="28rpx"></up-icon>
						<text class="address">{{groupInfo.address}}</text>
					</view>
					<text class="time">组队时间：{{groupInfo.start_date}} ~ {{groupInfo.end_date}}</text>
				</view>
			</view>
		</view>
		<!-- 选择名片 -->
		<view class="sign-box w100 flex-row-center" @click="()=>signShow=true">
			<text class="title">参与名片</text>
			<view class="sign-left flex-row-center">
				<text class="name">{{groupInfo.signName}}</text>
				<up-icon name="arrow-right" color="#A5A6A7" size="28rpx"></up-icon>
			</view>
		</view>
		<!-- 助教 -->
		<!-- 		<view class="w100">
			<chooseAssistantVue @changeAssistant="changeAssistants" :assistantIds="groupInfo.assistantId">
			</chooseAssistantVue>
		</view> -->
		<!-- 优惠券 -->
		<view class="w100">
			<chooseCoupon :useCost="groupInfo.cost" detail="1,4" @changeCouponItem="changeCoupon">
			</chooseCoupon>
		</view>
		<!-- 支付方式 -->
		<choosePayVue :payType="groupInfo.payType" @changePayType="changePayType" style="width: 100%;">
		</choosePayVue>

		<text class="instructions">请在组队开始时间之前完成支付，过期组队自动解散。</text>
		<!-- 协议 -->
		<view class="agreement-box flex-center">
			<up-checkbox labelColor="#999999" shape="circle" size="30rpx" labelSize="24rpx" label="已阅读并同意"
				activeColor="#8BDEB7" @change="changeChecked" name="agree" :checked="checked">
			</up-checkbox>
			<view class="content flex-row-center">
				<text class="agreement-name" @click="toProtocol(3)">《支付协议》</text>
			</view>
		</view>
	</view>

	<view class="payment-footer flex-center w100">
		<!-- 		<view class="cancel-box flex-center" @click="cancelGroup">
			<text class="text">取消组队</text>
		</view> width:'320rpx' -->
		<up-code :seconds="10" ref="uCodeRef" :startText="payText" changeText="x秒重新支付" :endText="payText"
			@change="codeChange"></up-code>
		<up-button :text="codeTips" @click="submitPayment" loadingText="提交中" :loading="payLoading"
			:customStyle="{'color':'#115B56',height:'72rpx',margin:'0'}"
			color="linear-gradient( 270deg, #94DEAC 0%, #7CDEC7 47%, #79DED3 100%)" shape="circle"></up-button>
	</view>
	<!-- 弹出组队 -->
	<up-popup :show="signShow" @close="closeSignShow" round="18rpx" closeable mode="bottom">
		<view class="choose-sign flex w100">
			<text class="title">选择组队名片</text>
			<template v-if="signlist.length>0">
				<view class="choose-content W100">
					<scroll-view scroll-y="true" style="height: 100%;width: 100%;">
						<view class="sign-item flex-row-center W100" v-for="(item,index) in signlist" :key="item.id"
							@click="changeSignId(item)">
							<view class="personnel-left">
								<view class="radio-box-active flex-center" v-if="groupInfo.signId==item.id">
									<up-icon name="checkbox-mark" color="#0A534F" size="28rpx"></up-icon>
								</view>
								<view class="radio-box" v-else></view>
							</view>
							<view class="personnel-right">
								<view class="personnel-head flex-row-center">
									<view class="name-box flex-row-center">
										<text class="name">{{item.real_name}}</text>
										<template>
											<up-icon name="man" v-if="item.gender==1" color="#2979ff"
												size="28rpx"></up-icon>
											<up-icon name="woman" v-if="item.gender==2" color="#F8BBC4"
												size="28rpx"></up-icon>
										</template>
									</view>
									<view class="status-box flex-center" v-if="item.default">
										<text class="text">默认</text>
									</view>
								</view>
								<text class="phone" v-if="item.newMobile">联系方式：{{item.newMobile}}</text>
								<text class="phone" v-else>联系方式：{{item.mobile}}</text>
							</view>
						</view>
					</scroll-view>
				</view>
				<view class="choseSign-footer w100 flex-center">
					<view class="add_box flex-center" @click="addSign">
						<up-icon name="plus" color="#7CDEC7" size="28rpx"></up-icon>
						<text class="text">新增名片</text>
					</view>
					<!-- 			<up-button text="确定" @click="submitSign"
						:customStyle="{'color':'#115B56',height:'68rpx',width:'280rpx',margin:'0'}"
						color="linear-gradient( 270deg, #94DEAC 0%, #7CDEC7 47%, #79DED3 100%)"
						shape="circle"></up-button> -->
				</view>
			</template>
			<view class="not-list-view" v-else>
				<text class="text">暂未添加名片信息~</text>
				<text class="btn" style="margin-left: 8rpx;" @click="addSign">立即添加</text>
			</view>
		</view>
	</up-popup>
</template>

<script setup>
	import {
		usePay
	} from '@/hooks/usePay.js';
	import {
		userInfoStore
	} from '../../stores/user';
	import {
		maskPhoneNumber
	} from '@/utils/utools.js';
	import {
		groupNotification
	} from '@/utils/groupNotification';
	import choosePayVue from '@/components/choosePay/choosePay.vue';
	import chooseCoupon from '@/components/chooseCoupon/chooseCoupon.vue';
	import chooseAssistantVue from '@/components/assistant/chooseAssistant.vue';
	const {
		appPay
	} = usePay();
	const userStore = userInfoStore();
	const addressInfo = ref(computed(() => userStore.addressInfo));
	const GroupId = ref(null);
	const payText = ref('确认支付');
	const signlist = ref([]);
	const codeTips = ref('');
	const checked = ref(false);
	const uCodeRef = ref(null);
	const signShow = ref(false);
	const orderInfo = ref(null);
	const chooseSignId = ref(0); //暂时选择名片id
	const payLoading = ref(false);
	const groupInfo = ref({
		groupId: 0,
		address: "",
		title: '',
		describe: '',
		imageList: [],
		cost: 0.00,
		status: 2, //组队状态
		start_date: 0,
		end_date: 0,
		signId: 0,
		signName: '',
		payType: 'wechat',
		couponId: 0,
		assistantId: '',
	});
	onLoad((option) => {
		console.log('参数', option);
		if (option.id) {
			GroupId.value = option.id;
			getGroupDetail(option.id);
			getSignList();
		} else {
			uni.$u.toast('没有找到相关订单')
		}
	});
	onMounted(() => {
		uni.$on('addSign', (data) => {
			console.log('监听到事件来自 addSign ，携带参数 msg 为：', data);
			if (data.type) {
				getSignList();
			}
		})
	})
	onUnload(() => {
		uni.$off('addSign');
	})
	const getGroupDetail = async (id) => { //获取组队详情
		const res = await $Api.group.getGroupDetail({
			id,
			lat: addressInfo.value?.latitude,
			lng: addressInfo.value?.longitude
		})
		if (res.code == 1) {
			setTimeout(() => {
				uni.hideLoading()
			}, 800)
			let imageList = []
			let newCost = 0;
			let levelInfo = null;
			if (res.data.image) {
				imageList = res.data.image.split(',')
			}
			if (res.data.juli) {
				res.data.juli = parseFloat(res.data.juli).toFixed(2)
			}
			if (res.data.end_date) {
				res.data.end_date = formatDate(res.data.end_date)
			}
			if (res.data.end_date) {
				res.data.start_date = formatDate(res.data.start_date)
			}
			if (res.data.type && res.data.type == 1 && res.data.number_people) { //是否全额支付
				res.data.cost = (res.data.cost * res.data.number_people).toFixed(2)
			}
			if (res.data.level && userStore.level_info && userStore.level_info.value) {
				levelInfo = userStore.level_info.value.find(val => val.vl_id == res.data.level)
			}
			payText.value = `确认支付（￥ ${res.data.cost}）`;
			codeTips.value = `确认支付（￥ ${res.data.cost}）`;
			groupInfo.value = {
				...groupInfo.value,
				...res.data,
				imageList,
				mainImg: imageList[0],
				levelInfo
			};
			console.log('groupInfo', groupInfo);
		} else {
			setTimeout(() => {
				uni.hideLoading();
				uni.$u.toast(res.msg);
			}, 800)
		}
	};
	const getSignList = async () => { //获取名片列表
		const res = await $Api.user.getSignList();
		if (res.code == 1) {
			res.data.list = res.data.list.map(val => {
				if (val.default === 1) { //保存默认的id，默认选中
					groupInfo.value.signId = val.id;
					groupInfo.value.signName = val.real_name;
				}
				if (val.mobile) {
					val.newMobile = maskPhoneNumber(val.mobile);
				}
				return val
			})

			signlist.value = res.data.list;
		} else {
			uni.$u.toast(res.msg);
		}
	};
	const submitSign = () => { //确认选择
		signShow.value = false;
	}
	const addSign = () => { //添加名片
		// signShow.value = false;
		uni.navigateTo({
			url: '/page_user/views/personnel'
		})
	}
	const changeSignId = (item) => { //切换名片
		// chooseSignId.value = item.id;
		groupInfo.value.signId = item.id;
		groupInfo.value.signName = item.real_name;
		signShow.value = false;
	};
	const closeSignShow = () => { //关闭选择
		signShow.value = false;
	}
	const changePayType = (item) => { //切换支付方式
		groupInfo.value.payType = item;
	}
	const codeChange = (text) => {
		codeTips.value = text;
	};
	const changeChecked = (e) => {
		checked.value = e;
	};
	const changeCoupon = (id) => { //切换优惠券
		groupInfo.value.couponId = id;
	}
	const changeAssistants = (list) => { //选择助教
		if (!list) return
		groupInfo.value.assistantId = list;
	}
	const cancelGroup = () => { //取消组队
		uni.showModal({
			title: '提示',
			content: '确定取消该组队？',
			success: async (res) => {
				if (res.confirm) {
					const res = await $Api.group.captainCancelGroup({
						id: GroupId.value
					}, true);
					if (res.code == 1) {
						uni.showLoading({
							title: '取消成功！'
						});
						// 重置列表
						setTimeout(() => {
							uni.navigateBack();
						}, 600)
					} else {
						uni.$u.toast(res.msg);
					}
				} else if (res.cancel) {
					// console.log('用户点击取消');
				}
			}
		});
	}
	const submitPayment = async () => { //提交支付
		if (!checked.value) {
			uni.$u.toast('请先阅读并勾选协议');
			return
		}
		if (!uCodeRef.value.canGetCode) {
			uni.$u.toast('倒计时结束后再支付');
			return
		}
		if (payLoading.value) return;
		if (!groupInfo.value.signId) {
			uni.$u.toast('请选择名片');
			return
		}
		payLoading.value = true;
		const res = await $Api.order.submitOrder({
			type: 'wechat',
			method: 'miniapp',
			relationId: GroupId.value,
			isBalance: groupInfo.value.payType === 'balance' ? 1 : 0,
			relationType: 'Group',
			signId: groupInfo.value.signId,
			orderId: orderInfo.value?.id || 0,
			userCouponId: groupInfo.value.couponId,
			assistantIds: groupInfo.value.assistantId || ''
		})
		if (res.code == 1) {
			const {
				data
			} = res;
			if (data.order) {
				data.order.time_expire = formatDate(data.order.time_expire);
				orderInfo.value = data.order;
				console.log('orderInfo.value', orderInfo.value);
			}
			if (groupInfo.value.payType === 'balance') { //余额支付
				uni.showToast({
					title: '支付成功'
				})
				pageIndex();
				allNotification(['groupStart', 'groupClose', 'groupEnd', 'assistantRefund'],
					() => {
						setTimeout(() => {
							payLoading.value = false;
							uni.navigateBack()
						}, 600)
					}); //打开通知
			} else { //微信支付
				appPay({
					provider: 'wxpay',
					timeStamp: data.pre_payment.timeStamp,
					nonceStr: data.pre_payment.nonceStr,
					package: data.pre_payment.package,
					signType: data.pre_payment.signType,
					paySign: data.pre_payment.paySign,
				}).then((res) => {
					console.log(res);
					if (res.code == 200) {
						uni.showToast({
							title: '支付成功'
						});
						pageIndex();
						allNotification(['groupStart', 'groupClose', 'groupEnd', 'assistantRefund'],
							() => {
								setTimeout(() => {
									payLoading.value = false;
									uni.navigateBack()
								}, 600)
							}); //打开通知
					} else if (res.code == 100) { //取消支付
						uni.$u.toast('已取消支付，请10s后重新支付');
						uCodeRef.value.start();
						payLoading.value = false;
					}
				}).catch((err) => {
					// console.log(err);
					payLoading.value = false;
					uni.$u.toast(err)
				})
			}

		} else {
			payLoading.value = false;
			uni.$u.toast(res.msg)
		}
	}
	const toProtocol = (type) => { //阅读协议
		uni.navigateTo({
			url: '/pages/protocol/protocol?type=' + type
		})
	}
	const pageIndex = () => {
		let pages = getCurrentPages() || [];
		if (pages.length < 2) return;
		let prevPage = pages[pages.length - 2];
		let prevPagePath = prevPage.route;
		if (prevPagePath === 'page_user/views/myTeam') {
			uni.$emit('restmyGroup', {
				msg: '重置我的组队列表',
				type: 1
			})
		}
	}
</script>

<style lang="scss" scoped>
	.payment-box {
		flex-direction: column;
		padding: 20rpx;
		padding-bottom: 182rpx;
	}

	.payment-content {
		flex-direction: column;
		height: 180rpx;

		.tips-box {
			margin-top: 24rpx;

			.tips {
				color: $description-color;
				font-size: 30rpx;
			}

			.timer {
				color: $timer-color;
				font-size: 30rpx;
				margin: 0 8rpx;
			}
		}

		.price-box text {
			color: $price-color;
		}

		.unit {
			font-size: 32rpx;
			font-weight: 500;
		}

		.price {
			font-size: 46rpx;
			font-weight: 800;
			margin-left: 8rpx;
		}
	}

	.team-content {
		width: 100%;
		background: #222528;
		border-radius: 20rpx;
		margin-bottom: 16rpx;
		box-sizing: border-box;
		padding: 40rpx 20rpx;

		.myTeamItem-head {
			justify-content: space-between;

			.myTeam_icon {
				width: 52rpx;
				height: 52rpx;
				margin-right: 12rpx;
			}

			.team-name {
				width: 360rpx;
				font-weight: bold;
				font-size: 34rpx;
				color: $name-color;
				text-overflow: ellipsis;
				white-space: nowrap;
				overflow: hidden;
			}

			.team-state {
				font-weight: 500;
				font-size: 24rpx;
				color: rgba(255, 255, 255, 0.6);
			}
		}

		.myTeamItem-content {
			margin-top: 32rpx;

			.myTeamItem-img {
				width: 160rpx;
				height: 160rpx;
				border-radius: 16rpx;
				margin-right: 32rpx;
				flex-shrink: 0;
			}

			.myTeamItem-info {
				.describe {
					color: $description-color;
					line-height: 36rpx;
					font-size: 30rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					word-break: break-all;
					-webkit-box-orient: vertical;
				}

				.address-box {
					margin: 16rpx 0;
				}

				.address {
					flex: 1;
					width: 0;
					color: $description-color;
					margin-left: 8rpx;
					font-size: 28rpx;
					text-overflow: ellipsis;
					white-space: nowrap;
					lines: 1;
					overflow: hidden;
				}

				.time {
					color: $description-color;
					font-size: 28rpx;
					line-height: 32rpx;
				}

			}
		}
	}

	.sign-box {
		justify-content: space-between;
		margin-top: 32rpx;

		.title {
			font-size: 32rpx;
			font-weight: bold;
			color: $name-color;
		}

		.sign-left {
			.name {
				color: $description-color;
				font-size: 28rpx;
				margin-right: 12rpx;
			}
		}
	}

	.payment-type {
		flex-direction: column;
		margin-top: 32rpx;

		.title {
			font-size: 36rpx;
			font-weight: bold;
			color: $name-color;
			margin-bottom: 32rpx;
		}

		.type-box {
			justify-content: space-between;
			padding: 24rpx;
			border-bottom: 2rpx solid #2B2E31;

			.type-left {
				.pay-icon {
					width: 32rpx;
					height: 32rpx;
					margin-right: 24rpx;
				}
			}

			.type {
				font-size: 32rpx;
				font-weight: bold;
				color: $name-color;
			}

			.choose-box {
				width: 36rpx;
				height: 36rpx;
				border-radius: 50%;
				background-color: $radios-color;
			}
		}

	}

	.instructions {
		margin-top: 36rpx;
		font-size: 32rpx;
		color: $description-color;
		line-height: 48rpx;
	}

	.payment-footer {
		padding: 0 32rpx;
		padding-bottom: env(safe-area-inset-bottom);
		// justify-content: space-evenly;
		background-color: #191C1F;
		height: 162rpx;
		position: fixed;
		bottom: 0;
		border-top: 2rpx solid #303335;

		.cancel-box {
			width: 320rpx;
			height: 72rpx;
			border-radius: 36rpx;
			border: 1rpx solid $cancel-btn-color;

			.text {
				font-family: 28rpx;
				color: $cancel-btn-color;
			}
		}

		.price-box {
			color: #7CDED4;
			font-weight: bold;

			.icon {
				font-size: 28rpx;
			}

			.price {
				font-size: 44rpx;
				margin-left: 6rpx;
			}
		}

		.payment-btn {
			width: 50%;
		}
	}

	.choose-sign {
		padding: 36rpx;
		height: 60vh;
		flex-direction: column;
		flex-direction: column;
		background-color: #222528;
		border-radius: 18rpx 18rpx 0 0;

		.title {
			font-weight: bold;
			font-size: 34rpx;
			color: rgba(255, 255, 255, 0.87);
			line-height: 40rpx;
		}

		.choose-content {
			flex: 1;
			margin: 24rpx 0;
			overflow: hidden;

			.sign-item {
				padding: 20rpx 0;

				&:not(:last-child) {
					border-bottom: 1rpx solid #373B3E;
				}
			}
		}

		.radio-box {
			width: 36rpx;
			height: 36rpx;
			border-radius: 50%;
			border: 1rpx solid #ccc;
			margin-right: 18rpx;
			box-sizing: border-box;
		}

		.radio-box-active {
			width: 36rpx;
			height: 36rpx;
			border-radius: 50%;
			background-color: #7EDE9E;
			margin-right: 18rpx;
		}

		.choseSign-footer {
			height: 72rpx;
			justify-content: space-evenly;
		}

		.add_box {
			width: 280rpx;
			height: 68rpx;
			border-radius: 47rpx;
			border: 2rpx solid $btn-plain-color;

			.text {
				font-weight: 800;
				font-size: 30rpx;
				color: $btn-plain-color;
				margin-left: 12rpx;
			}
		}

		.personnel-left {
			flex-shrink: 0;
		}

		.personnel-right {
			margin-left: 24rpx;
			flex: 1;
			display: flex;
			flex-direction: column;
		}

		.personnel-head {
			width: 100%;
			justify-content: space-between;

			.name {
				font-size: 32rpx;
				font-weight: bold;
				color: $title-color;
				margin-right: 12rpx;
			}
		}

		.phone {
			color: $description-color;
			font-size: 28rpx;
			margin-top: 18rpx;
		}

		.status-box {
			width: 96rpx;
			height: 48rpx;
			border-radius: 12rpx;
			border: 1rpx solid $attention-color;
			color: $attention-color;

			.text {
				color: $attention-color;
				font-weight: bold;
				font-size: 28rpx;
			}
		}
	}

	.agreement-box {
		width: 100%;
		margin-top: 54rpx;

		.content {
			font-weight: 500;
			font-size: 24rpx;
			margin-left: 8rpx;

			.text {
				color: #999999;
			}

			.agreement-name {
				color: #559992;
			}
		}
	}
</style>